package com.mmd.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mmd.bean.CODE;
import com.mmd.common.bean.KDniaoLogisticsResult;
import com.mmd.common.bean.Traces;
import com.mmd.common.entity.MmdOrder;
import com.mmd.exception.GameException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author cyq
 * @Date 2019/10/13 16:16
 * @Description
 **/
public class PullLogisticsUtils {
    private static final Logger logger = LoggerFactory.getLogger(PullLogisticsUtils.class);

    private static CloseableHttpClient httpClient = HttpClients.createDefault();

    public static KDniaoLogisticsResult pullLogisticsInfo(MmdOrder order, String appkey, String userid) {
        String url = "http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
//        order.setLogisticsCompanyCode("UPS");
//        order.setLogisticsNo("1ZE8005X0478352481");
//        order.setLogisticsCompanyCode("FEDEX_GJ");
//        order.setLogisticsNo("775729802559");
        try {
            Map<String, Object> bparam = new HashMap<>();
            bparam.put("ShipperCode", order.getLogisticsCompanyCode());
            bparam.put("LogisticCode", order.getLogisticsNo());
            String md5Str = DigestUtils.md5DigestAsHex((JSON.toJSONString(bparam) + appkey).getBytes());
            String sign = new String(Base64.getEncoder().encode(md5Str.getBytes()));

            StringBuilder sb = new StringBuilder();
            sb.append("EBusinessID=");
            sb.append(userid);
            sb.append("&");
            sb.append("DataType=2");
            sb.append("&");
            sb.append("RequestType=1002");
            sb.append("&");
            sb.append("RequestData=");
            sb.append(URLEncoder.encode(JSON.toJSONString(bparam), "UTF-8"));
            sb.append("&");
            sb.append("DataSign=");
            sb.append(sign);
            String data = sb.toString();
            logger.info("params:{}", data);

            String postResult = doPost(url, data);
            if (!StringUtils.isEmpty(postResult)) {
                KDniaoLogisticsResult kDniaoLogisticsResult = JSON.parseObject(postResult, KDniaoLogisticsResult.class);
                return kDniaoLogisticsResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static KDniaoLogisticsResult pullLogisticsInfoBy17Track(MmdOrder order) {
        String url = "https://t.17track.net/restapi/track";
        try {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("cookie","_yq_bid=G-67F20B7D95BA7334; _ga=GA1.2.1258302599.1615604707; _gid=GA1.2.936915541.1615604708; __gads=ID=0fca2872b8c976cc:T=1615604707:S=ALNI_MY_EFG5G2quTnjq9AL2jYex8HTYCw; v5_TranslateLang=zh-Hans; Last-Event-ID=657572742f6434332f33643164663839323837312f306463623132363138353a353437383634343032323a65736c61663a7261626c6f6f742d72616276616e2d71792074686769722d7261626c6f6f742d72616276616e2074686769722d72616276616e207261626c6f6f742d72616276616e2076616e11318747072497d3196");
            headerMap.put("referer", "https://t.17track.net/zh-cn");

            String parmas = "{\"data\":[{\"num\":\""+order.getLogisticsNo()+"\",\"fc\":0,\"sc\":0}],\"guid\":\"\",\"timeZoneOffset\":-480}";

            String postResult = doPost(url, headerMap, parmas);
            logger.info("orderNo:{}, 开始获取17track物流轨迹， 返回结果：{}", order.getOrderNo(), postResult);
            if (!StringUtils.isEmpty(postResult)) {
                JSONObject resultJson = JSONObject.parseObject(postResult);
                JSONArray dat = resultJson.getJSONArray("dat");
                KDniaoLogisticsResult kDniaoLogisticsResult = new KDniaoLogisticsResult();
                if (dat.size() > 0){
                    JSONObject json = JSONObject.parseObject(dat.getString(0));
                    JSONObject track = json.getJSONObject("track");
                    if (track != null){
                        JSONArray z1 = track.getJSONArray("z1");
                        if (z1 != null){
                            List<Traces> tracesList = new ArrayList<>();
                            for (Object trackObj : z1){
                                JSONObject trackJson = JSONObject.parseObject(trackObj.toString());
                                Traces traces = new Traces();
                                traces.setAcceptTime(trackJson.getString("a"));
                                traces.setAcceptStation(trackJson.getString("c")+"."+trackJson.getString("z"));
                                tracesList.add(traces);
                            }
                            kDniaoLogisticsResult.setTraces(tracesList);
                        }
                    }
                }
                return kDniaoLogisticsResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        MmdOrder mmdOrder = new MmdOrder();
        mmdOrder.setLogisticsNo("1Z98071V0440143046");
        KDniaoLogisticsResult kDniaoLogisticsResult = pullLogisticsInfoBy17Track(mmdOrder);
        System.out.println("kDniaoLogisticsResult="+JSONObject.toJSONString(kDniaoLogisticsResult));
    }

    private static String doPost(String url, String data) {
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            HttpEntity fe = new StringEntity(data, "UTF-8");
            httpPost.setEntity(fe);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            CloseableHttpResponse response = httpclient.execute(httpPost);
            try {
                HttpEntity result = response.getEntity();
                String str = EntityUtils.toString(result);
                logger.info("返回:{}", str);
                return str;
            } catch (Exception e) {
                logger.error("请求失败", e);
            } finally {
                response.close();
            }
        } catch (Exception e2) {
            logger.error("请求失败", e2);
            e2.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     *post请求
     */
    public static String doPost(String url,Map<String, String> headerMap,String jsonStr) {
        logger.info("调用doPost接口请求参数为:url:{}，请求头：{}，参数：{}",url,headerMap,jsonStr);
        String result = "";
        HttpPost httpPost = new HttpPost(url);
        //设置请求头
        httpPost.addHeader("Content-Type", "application/json");
        for (String key : headerMap.keySet()) {
            httpPost.addHeader(key, headerMap.get(key));
        }
        StringEntity requestEntity = new StringEntity(jsonStr,"utf-8");
        requestEntity.setContentEncoding("UTF-8");
        httpPost.setEntity(requestEntity);
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK){
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity, "UTF-8");
            }else {
                throw new GameException(new CODE(9999, "请求17track物流轨迹失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            httpPost.abort();
        }
        return result;
    }
}
